/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webanovare.bb;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.icefaces.application.PushRenderer;

@ManagedBean(name = "text")
@ViewScoped
public class ChatBB implements Serializable {

    public static final String CHAT_PUSH_GROUP = "chat";
    @ManagedProperty(value = "#{messageBean}")
    private MessageBB messageBean;
    private String userName;
    private String message;

    public ChatBB() {
        PushRenderer.addCurrentSession(CHAT_PUSH_GROUP);
        FacesContext fcontext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) fcontext.getExternalContext().getSession(false);
        //userName = session.getId();
        
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        userName = request.getRemoteUser();
        
        if (userName == null) {
            userName = "guest" + ((int)(Math.random() * Integer.MAX_VALUE));
        }
    }
    public void setMessageBean(MessageBB messageBean) {
        this.messageBean = messageBean;
    }

    public String update() {
        if (message != null && message.length() > 0) {
            messageBean.addToList(userName, message);
            PushRenderer.render(CHAT_PUSH_GROUP);
        }
        this.message = "";

        return null;
    }

    public void setText(String text) {
        this.message = text;
    }

    public String getText() {
        return message;
    }

    public String getSessionId() {
        return userName;
    }

    public void setSessionId(String id) {
    }
}